<?php
/**
 * 生成ical格式，此格式显示数据最全面
 */
class _interface extends __interface {
	
	/**
	 * (non-PHPdoc)
	 *
	 * @see __interface::dispose_data()
	 */
	public function dispose_data() {
		global $cache;
		// 获取要显示开开始和结束日期
		$this->day_begin = strtotime ( date ( "Y-m-d" ) );
		$this->day_end = strtotime ( date ( "Y-m-d" ) );
		
		$s = "BEGIN:VCALENDAR\r\n";
		$s .= "PRODID:-//mdeve.com//天气、农历、节日//CN\r\n";
		$s .= "VERSION:2.0\r\n";
		$s .= "METHOD:PUBLISH\r\n";
		$s .= "X-CALSTART:" . date ( "Ymd", $this->day_begin ) . "T000000Z\r\n";
		$s .= "X-CALEND:" . date ( "Ymd", dateadd ( 'day', max($this->style["festival_before_days"], $this->style["festival_later_days"]), $this->day_begin ) ) . "T000000Z\r\n";
		$s .= "X-WR-CALNAME:" . $this->weather_data['city_2']."-".$this->weather_data['city_1'] . "天气、农历、节日\r\n";
		$s .= "X-APPLE-CALENDAR-COLOR:#990000\r\n";
		$s .= "X-WR-TIMEZONE:Asia/Shanghai\r\n";
		//print_r($this->weather_data);exit;
		// 如果要显示天气
		$weather_data = array ();
		// /////////////////////////////////////////////////////////////////////////////////////////////////////
		if ($this->style ["show_weather"]) {
			// 天气预警
			if(isset($this->weather_data["alarm"]) && sizeof($this->weather_data["alarm"])){
				foreach ($this->weather_data["alarm"] as $r){
					$title = $r["w1"]. $r["w2"]. $r["w5"]. $r["w7"]. "预警";
					$detail = $r["w9"];
					// 建立日历条目
					$s .= "BEGIN:VEVENT\r\n";
					$s .= "CLASS:PUBLIC\r\n";
					$s .= "CREATED:" . date ( "Ymd" ) . "T" . date ( "His" ) . "Z\r\n";
					$s .= "DESCRIPTION:{$detail} \r\n";
					$s .= "DTSTART;TZID=Asia/Chongqing:" . date("Ymd", strtotime($r["w8"])) . "T" . date("His") . "\r\n";
					$s .= "DTEND;TZID=Asia/Chongqing:" . date ( "Ymd") . "T235959" . "\r\n";
					$s .= "DTSTAMP:" . date ( "Ymd") . "T" . date ( "His" ) . "Z\r\n";
					$s .= "LAST-MODIFIED:" . date ( "Ymd" ) . "T" . date ( "His" ) . "Z\r\n";
					$s .= "LOCATION:" . ($this->weather_data ["city_1"]=="城区" ? $this->weather_data ["city_2"] : $this->weather_data ["city_1"]) . "\r\n";
					$s .= "SEQUENCE:" . date("ndHi") . "\r\n";
					$s .= "PRIORITY:6\r\n";
					$s .= "TRANSP:TRANSPARENT\r\n";
					$s .= "UID:" . $this->create_uid ($r["w8"], "a") . "\r\n";
					$s .= "STATUS:TENTATIVE\r\n";
					$s .= "CATEGORIES:FREE\r\n";
					$s .= "SUMMARY:{$title}\r\n";
					$s .= "END:VEVENT\r\n";
				}
			}

			// 处理今天天气
			$date = strtotime ( $this->weather_data['update_time'] );
			// 实时温度信息
			$detail = "";
			if(array_key_exists("realtime", $this->weather_data)){
				$detail .= "实时天气：" . $this->weather_data ['realtime'] ['weather'] . "\\n";
				$detail .= "实时温度：" . $this->weather_data ['realtime'] ['tempn'] . "\\n";
				$detail .= "天气网发布时间：" . $this->weather_data['update_time']. "\\n";
				$detail .= "更新时间：" . $this->weather_data ['lastupdate'] . "\\n";
			}
			// AQI信息
			if(array_key_exists("air_aqi", $this->weather_data)){
				//$detail .= "\\n---------- 空气质量指数 ----------\\n";
				if($this->weather_data["air_aqi"]<=50) $aqi_level = "优";
				if($this->weather_data["air_aqi"]>50 && $this->weather_data["air_aqi"]<=100) $aqi_level = "良";
				if($this->weather_data["air_aqi"]>100 && $this->weather_data["air_aqi"]<=150) $aqi_level = "轻度污染";
				if($this->weather_data["air_aqi"]>150 && $this->weather_data["air_aqi"]<=200) $aqi_level = "中度污染";
				if($this->weather_data["air_aqi"]>200 && $this->weather_data["air_aqi"]<=300) $aqi_level = "重度污染";
				if($this->weather_data["air_aqi"]>300) $aqi_level = "严重污染";
				$detail .= "空气质量：{$aqi_level}  AQI：" . $this->weather_data["air_aqi"] . "\\n";
			}

			// 天气详细情况
			$detail .= "\\n---------- 天气详细情况 ----------\\n";
			$detail .= "天气：" . $this->weather_data["today"]["weather_day"]. " 转 ". $this->weather_data["today"]["weather_night"]. "\\n";
			$detail .= "风向：". $this->weather_data["today"]["wind_direction_day"].$this->weather_data["today"]["wind_power_day"]. " 转 " . $this->weather_data["today"]["wind_direction_night"].$this->weather_data["today"]["wind_power_night"]. "\\n";
			$detail .= "温度：". $this->weather_data["today"]["temperature_day"]. "~". $this->weather_data["today"]["temperature_night"]. "\\n";
			$detail .= "日出：". $this->weather_data["today"]["sun_up"]. "，日落：". $this->weather_data["today"]["sun_down"] . "\\n";

			// 生活指数
			if ($this->style ["show_weather_index"]) {
				$detail .= "\\n---------- 生活指数 ----------\\n";
				if(isset($this->weather_data["index_hot"])){
					foreach ( $this->weather_data["index_hot"] as $r ) {
						$detail .= $r["title"] . "：" . $r ["important"] . "，" . $r ["content"] . "\\n\\n";
					}
				}
			}
			
			// 通知栏显示标题
			$title = $this->weather_data["realtime"]["weather"]. " ";
			$title .= $this->weather_data["realtime"]["temp"]. "~". $this->weather_data["realtime"]["tempn"]. " ";
			if($this->weather_data["realtime"]["wd"] != "无持续风向") {
				$title .= $this->weather_data["realtime"]["wd"] . $this->weather_data["realtime"]["ws"] . " ";
			}
			$s .= $this->create_vevent($date, $title, $detail, "w");

			// 最近7天天气
			for($i=1; $i<sizeof($this->weather_data["day_7"]); $i++){
				if($this->style ["weather_days"] < $i+1) break;
				// 天气详细情况
				$detail = "\\n---------- 天气详细情况 ----------\\n";
				$detail .= "天气：". $this->weather_data["day_7"][$i]["weather"]. "\\n";
				$detail .= "温度：". $this->weather_data["day_7"][$i]["temperature_1"]. "~".$this->weather_data["day_7"][$i]["temperature_2"]. "\\n";
				$detail .= "风向：". $this->weather_data["day_7"][$i]["wind_direction_1"]. "~". $this->weather_data["day_7"][$i]["wind_direction_2"]. " ". $this->weather_data["day_7"][$i]["wind_power"]. "\\n";
				// 通知栏显示标题
				$title = $this->weather_data["day_7"][$i]["weather"]. " ";
				$title .= $this->weather_data["day_7"][$i]["temperature_1"]. "~".$this->weather_data["day_7"][$i]["temperature_2"]. "\\n";
				// 建立日历条目
				$s .= $this->create_vevent($date+86400*$i, $title, $detail, "w");
			}
			
			// 7-15天天气
			for($i=0; $i<sizeof($this->weather_data["day_15"]); $i++){
				if($this->style ["weather_days"] < 7+$i) break;
				// 天气详细情况
				$detail = "\\n---------- 天气详细情况 ----------\\n";
				$detail .= "天气：". $this->weather_data["day_15"][$i]["weather"]. "\\n";
				$detail .= "温度：". $this->weather_data["day_15"][$i]["temperature"]. "\\n";
				$detail .= "风向：". $this->weather_data["day_15"][$i]["wind_direction"]. $this->weather_data["day_15"][$i]["wind_power"]. "\\n";
				// 通知栏显示标题
				$title = $this->weather_data["day_15"][$i]["weather"]. " ". $this->weather_data["day_15"][$i]["temperature"]. "\\n";
				// 建立日历条目
				$s .= $this->create_vevent($date+86400*(7+$i), $title, $detail, "w");
			}

		}
		///////////////////////////////////////////////////////////////////////////////////////////////////////
		
		///////////////////////////////////////////////////////////////////////////////////////////////////////
		for($i = -$this->style ["festival_before_days"]; $i <= $this->style ["festival_later_days"]; $i ++) {
			$date = date ( "Y-m-d", dateadd ( "day", $i ) );
			$date = strtotime ( $date );
			// 如果要显示农历
			$festival_data = array ();
			// 如果要显示农历
			if ($this->style ["show_festival"]) {
				if ($this->style ["festival_before_days"] > 0)
					$this->day_begin = dateadd ( "day", - $this->style ["festival_before_days"], strtotime ( date ( "Y-m-d 0:0:0" ) ) );
				if ($this->style ["festival_later_days"] > $this->style ["show_weather"])
					$this->day_end = dateadd ( "day", $this->style ["festival_later_days"], strtotime ( date ( "Y-m-d 0:0:0" ) ) );
				$festival = init_festival ();
				$festival_data = $festival->get ( $date );
				
				$day_info = array ();
				$day_info [] = $festival_data ["lunar"];
				// 获取固定节日
				if (isset ( $festival_data ["festival_fixed"] )) {
					foreach ( $festival_data ["festival_fixed"] as $r ) {
						$day_info [] = $r;
					}
				}
				// 获取不固定节日
				if (isset ( $festival_data ["festival_unstable"] )) {
					foreach ( $festival_data ["festival_unstable"] as $r ) {
						$day_info [] = $r;
					}
				}
				// 获取农历节气
				if (isset ( $festival_data ["solar_festival"] )) {
					foreach ( $festival_data ["solar_festival"] as $r ) {
						$day_info [] = $r;
					}
				}
				// 获取农历节日
				if (isset ( $festival_data ["lunar_festival"] )) {
					foreach ( $festival_data ["lunar_festival"] as $r ) {
						$day_info [] = $r;
					}
				}
				// 获取数据完毕，开始生成ics文件
				$info = "---------- 今日详情 ----------\\n" . $day_info [0] . "\\n";
				$detail = "";
				
				if (sizeof ( $day_info ) > 1) {
					for($x = 1; $x < sizeof ( $day_info ); $x ++) {
						$info .= $day_info [$x] ["title"];
						if (isset ( $day_info [$x] ["beginyear"] )) {
							$num = date ( "Y" ) - $day_info [$x] ["beginyear"] + 1;
							$info .= " （第{$num}个）";
						}
						$info .= "\\n";
						
						$detail .= "\\n---------- " . $day_info [$x] ["title"] . " ----------\\n";
						$detail .= $day_info [$x] ["content"] . "\\n";
					}
				}
				
				// 获取黄历
				if (isset ( $festival_data ["almanac"] )) {
					$detail .= "\\n---------- 今日黄历 ----------\\n";
					foreach ( $festival_data ["almanac"] as $almanac ) {
						$detail .= "{$almanac}\\n";
					}
				}
				
				if ($i == 0) { // 如果是今天，开始时间则为当前
					$detail .= "\\n\\n更新时间：" . date ( "Y-m-d H:i:s" ) . "\\n";
				}
				$s .= "BEGIN:VEVENT\r\n";
				$s .= "CLASS:PUBLIC\r\n";
				$s .= "CREATED:" . date ( "Ymd" ) . "T" . date ( "His" ) . "Z\r\n";
				$s .= "DESCRIPTION:{$info}\\n{$detail}\r\n";
				$s .= "DTSTAMP:" . date ( "Ymd", $date ) . "T" . date ( "His" ) . "Z\r\n";
				if ($i == 0) { // 如果是今天，开始时间则为当前
					$s .= "DTSTART;TZID=Asia/Chongqing:" . date ( "Ymd" ) . "T" . date ( "His", time() + 300 ) . "\r\n";
				} else {
					$s .= "DTSTART;TZID=Asia/Chongqing:" . date("Ymd", $date) . "T235959\r\n";
				}
				$s .= "DTEND;TZID=Asia/Chongqing:" . date ( "Ymd", dateadd ( 'day', 1, $date ) ) . "T000000" . "\r\n";
				$s .= "LAST-MODIFIED:" . date ( "Ymd" ) . "T" . date ( "His" ) . "Z\r\n";
				//$s .= "SEQUENCE:" . date("ndHi") . "\r\n";
				$s .= "SEQUENCE:" . rand(100000,999999) . "\r\n";
				$s .= "PRIORITY:6\r\n";
				$s .= "TRANSP:TRANSPARENT\r\n";
				$s .= "UID:" . $this->create_uid ($date, "f") . "\r\n";
				$s .= "STATUS:TENTATIVE\r\n";
				$s .= "CATEGORIES:FREE\r\n";
				$s .= "SUMMARY:" . $day_info [0] . "\r\n";
				$s .= "END:VEVENT\r\n";
			}
		}
		
		// /////////////////////////////////////////////////////////////////////////////////////////////////////
		
		$s .= "END:VCALENDAR";
		
		header ( "Content-Type: text/calendar; charset=utf-8" );
		echo $s;
	}
	
	
	private function create_vevent($date, $title, $detail, $flag="w"){
		///////////////////////////////////////////////////////////////
		// 临时解决,需要在 get.php 里处理多了一个温度单位的问题,这里暂时解决
		$title = str_replace("℃℃","℃", $title);
		///////////////////////////////////////////////////////////////
		$s = "BEGIN:VEVENT\r\n";
		$s .= "CLASS:PUBLIC\r\n";
		$s .= "CREATED:" . date ( "Ymd" ) . "T" . date ( "His" ) . "Z\r\n";
		$s .= "DESCRIPTION:{$detail} \r\n";
		// IOS8上有个奇怪的BUG，如果多个条目开始时间一样，今日屏幕下就只显示最后一个，其他的显示成黑色的框框，待解决
		if(strtotime(date("Y-m-d 23:59:59")) >= $date) {	// 今天
			$s .= "DTSTART;TZID=Asia/Chongqing:" . date("Ymd", $date) . "T" . date("His") . "\r\n";
		}else{
			$s .= "DTSTART;TZID=Asia/Chongqing:" . date("Ymd", $date) . "T235959\r\n";
		}
		// 改成显示全天
		//$s .= "DTSTART;TZID=Asia/Chongqing:" . date("Ymd", $date) . "T000000\r\n";
		$s .= "DTEND;TZID=Asia/Chongqing:" . date ( "Ymd", dateadd ( 'day', 1, $date ) ) . "T000000" . "\r\n";
		$s .= "DTSTAMP:" . date ( "Ymd", dateadd ( 'day', - 1, $date ) ) . "T" . date ( "His" ) . "Z\r\n";
		$s .= "LAST-MODIFIED:" . date ( "Ymd" ) . "T" . date ( "His" ) . "Z\r\n";
		$s .= "LOCATION:" . ($this->weather_data ["city_1"]=="城区" ? $this->weather_data ["city_2"] : $this->weather_data ["city_1"]) . "\r\n";
		$s .= "SEQUENCE:" . date("ndHi") . "\r\n";
		$s .= "PRIORITY:6\r\n";
		$s .= "TRANSP:TRANSPARENT\r\n";
		$s .= "UID:" . $this->create_uid ($date, $flag) . "\r\n";
		$s .= "STATUS:TENTATIVE\r\n";
		$s .= "CATEGORIES:FREE\r\n";
		$s .= "SUMMARY:{$title}\r\n";
		$s .= "END:VEVENT\r\n";
		
		return $s;
	}
	
	
	private function create_uid($date, $flag="weather") {
		//return strtoupper ( $this->randomstr ( 8 ) . "-" . $this->randomstr ( 4 ) . "-" . $this->randomstr ( 4 ) . "-" . $this->randomstr ( 4 ) . "-" . $this->randomstr ( 12 ) );
		if(strtotime($date)>0) $date = strtotime($date);
		return "{$flag}_".date("Ymd", $date). "@mdeve.com";
	}
	private function randomstr($length, $numeric = 0) {
		mt_srand ( ( double ) microtime () * 1000000 );
		if ($numeric) {
			$hash = sprintf ( '%0' . $length . 'd', mt_rand ( 0, pow ( 10, $length ) - 1 ) );
		} else {
			$hash = '';
			$chars = 'ABCDEF0123456789';
			$max = strlen ( $chars ) - 1;
			for($i = 0; $i < $length; $i ++) {
				$hash .= $chars [mt_rand ( 0, $max )];
			}
		}
		return $hash;
	}
}